package com.cn.hu.filter;

import java.io.IOException;

import javax.servlet.Filter;
import javax.servlet.FilterChain;
import javax.servlet.FilterConfig;
import javax.servlet.ServletException;
import javax.servlet.ServletRequest;
import javax.servlet.ServletResponse;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;

import org.apache.commons.lang.StringUtils;
import org.apache.commons.logging.Log;
import org.apache.commons.logging.LogFactory;


public class CheckFilter implements Filter  {

	private static final Log log = LogFactory.getLog(CheckFilter.class);
	
	@Override
	public void destroy() {
		// TODO Auto-generated method stub
		
	}

	@Override
	public void doFilter(ServletRequest request, ServletResponse response,
			FilterChain chain) throws IOException, ServletException {
		// TODO Auto-generated method stub
		HttpServletRequest req = (HttpServletRequest) request;
		HttpServletResponse res = (HttpServletResponse) response;
		//如果session超时，则进入登录页并提示超时，请重新登录
		String requestUri = req.getRequestURI();
		Object user =req.getSession().getAttribute("user");
		
		req.setCharacterEncoding("utf-8");
		String [] arrays=req.getRequestURI().split("/");
		String currentUrl=arrays[arrays.length-1];
		String _sel=request.getParameter("_sel");
		System.out.println("the uri is --->"+requestUri);
		System.out.println("currentUrl is -->"+currentUrl);
		if(!StringUtils.isEmpty(_sel)){
			request.setAttribute("_sel",_sel);
			log.debug("the _sel is ----------->"+_sel);
		}
		//未登录
		if(user!=null){
			//res.sendRedirect(req.getContextPath()+"/web/login.htm");
			chain.doFilter(req, res);
		}else{
			if(currentUrl.hashCode()=="code.htm".hashCode()
					||currentUrl.hashCode()=="login.htm".hashCode()
					||currentUrl.hashCode()=="doLogin.htm".hashCode()
					||currentUrl.hashCode()=="index.htm".hashCode()
					){
				chain.doFilter(req, res);
			}else{
				request.getRequestDispatcher("login.htm").forward(request, response);
			}
			
		}
	}
	
	@Override
	public void init(FilterConfig arg0) throws ServletException {
		// TODO Auto-generated method stub
		
	}

}
